#ifndef Use_h
#define Use_h
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <vector>
#include<memory>

#include"InetAddr.hpp"
#include"Log.hpp"

#define CONV(v) (struct sockaddr *)(v)
using namespace log;
using namespace std;

class UserInterface
{
    public:
    virtual ~UserInterface() = default;
    virtual void SendTo(int sockfd, const std::string &message) = 0;
};

class User : public UserInterface
{
    public:

    User(const InterAddr &addr)
        : _addr(addr)
    {

    }

    void SendTo(int sockfd, const std::string &message) override
    {
        int n = sendto(sockfd, message.c_str(), message.size(), 0, _addr.NetAddr(), _addr.NetAddrLen());
        if (n < 0)
            perror("发送错误:");
    }
    InterAddr& Addr(){return _addr;};

private:
    InterAddr _addr;
};


class Manage
{
public:
    Manage(){};
    ~Manage(){};


    bool AddUser(InterAddr addr)
    {
        
        for(auto&ptr:_users)
        {

            if(ptr!=nullptr&&ptr->Addr()==addr)
            {
                LOG(LogLevel::INFO)<<"已经存在该用户"<<addr.Ip();
                ptr->Addr().Exchange(addr);
                return false;
            }
        }
        _users.push_back(make_shared<User>(addr));
        LOG(LogLevel::INFO)<<"添加新用户成功ip:"<<addr.Ip();
        return true;
    }


    void Router(int sockfd, const std::string &message)
    {
        for (auto &user :_users)
        {
            user->SendTo(sockfd, message);
        }
    }


private:
  std::vector<shared_ptr<User>> _users;  
};
#endif